package models

import (
	"fmt"
	"iptv_server/v3/src/models/homevideo_model"
	"iptv_server/v3/src/settings"
	"strings"
)

type VideoDetail struct {
	homevideo_model.Detail
	Vod_play_url  string `json:"vod_play_url,omitempty"`
	Vod_play_from string `json:"vod_play_from"` // not null
}

type Video struct {
	List []*VideoDetail `json:"list"`
}

// for category
func convertDetails(ret *homevideo_model.Category) (*homevideo_model.Category, error) {
	for i, d := range ret.Details {
		if !isHttpUrl(d.Pic) {
			d.Pic = getUrl(d.Pic)
			ret.Details[i] = d
		}

		// if len(d.IsFolder) > 0 {
		// 	d.VodId = d.IsFolder
		// 	// remark := "合集"
		// 	// if len(ret.Details[i].Remark) > 0 {
		// 	// 	remark += ":" + ret.Details[i].Remark
		// 	// }
		// 	// ret.Details[i].Remark = remark
		// 	// ret.Details[i].Type_tag = folder | cover

		// 	// 其他集合: SubId 只存在于 子目录, 比如比例!
		// 	//// 然后 就可以根据 这个 新的VodID 自由发挥 进行url请求.
		// } else {
		// 	d.VodId = fmt.Sprintf("%d", d.ID)
		// }

	}

	return ret, nil
}

func convertDetailPlayListToString(detail *homevideo_model.Detail) (*Video, error) {
	// copy value
	d2 := &VideoDetail{}

	if !isHttpUrl(detail.Pic) {
		detail.Pic = getUrl(detail.Pic)

	}

	// if detail.RedirectCateID > 0 {
	// 	// 子目录 根本不会  使用这个接口请求 detail列表!!

	// 	detail.ID = detail.RedirectCateID // detail id 转成组 id
	// 	// d2.Type_tag=folder | cover
	// 	detail.Name = "💼合集" + detail.Name
	// } else {
	fmt.Println("detail name=", detail.Name)
	//

	if len(detail.Plays) > 0 {
		play_list := make([]string, 0, 16)
		for i, v := range detail.Plays {
			var s string
			if len(v.Name) == 0 {
				s = fmt.Sprintf("%d$%d", i+1, v.ID)
			} else {
				s = fmt.Sprintf("%d %s$%d", i+1, v.Name, v.ID)
			}
			play_list = append(play_list, s)
		}
		d2.Vod_play_url = strings.Join(play_list, "#")
		// fmt.Printf("d2.Vod_play_url: %v\n", d2.Vod_play_url)
	}
	d2.Vod_play_from = "HomeVideo"
	// }
	d2.Detail = *detail
	vi := &Video{}
	vi.List = append(vi.List, d2)
	return vi, nil
}

func convertPlay(p *homevideo_model.Play) (*homevideo_model.Play, error) {
	if isHttpUrl(p.Url) {
		return p, nil
	}
	p.Url = getUrl(p.Url)
	return p, nil
}

func getUrl(p string) string {
	if strings.HasPrefix(p, "/") {
		return fmt.Sprintf("%s%s", settings.SiteDomain, p)
	}

	return fmt.Sprintf("%s%s/%s", settings.SiteDomain, settings.UrlPath_StaticFile, p)
}

func isHttpUrl(u string) bool {
	if len(u) < 7 {
		return false
	}
	pre := strings.ToLower(u[:7])
	if strings.HasPrefix(pre, "http://") || strings.HasPrefix(pre, "https://") {
		return true
	}
	return false
}
